<?php

class FeedbackController extends MyClass_Action {
	protected $controller;
	protected $action;
	protected $_user;
	
	public function init() {
		
		$this->commonAction();	
	
	}
	//用户首页
	public function indexAction() {
		try {
			
			$type =   $this->_request->getParam ( 'type' ); 
			$this->view->type=$type;		
			$where =' and 1=1';
			if($type == 'isover'){
				$where .=' and isover=1';
			  }else if($type == 'ispend'){
				  //待处理
				  $where .=' and ispending=0 and isover =0';
			  }else if($type == 'isprocess'){
				  //处理中的
				  $where .=' and ispending=1 and isover =0';
			  } 
			$count = 20;
			$curpage = ( int ) $this->_request->getParam ( 'page' );
	     	if (! $curpage)
    				$curpage = 1;
			$this->view->pageNum=$curpage;		
    			$offset = ($curpage - 1) * $count; 
			$sql='select SQL_CALC_FOUND_ROWS *  from `feedback` where  isdelete=0  '.$where.'  order by isover,addtime desc limit '.$offset.','.$count; 
			//echo $sql;exit;
			  
			$result1=$this->_dbAdapter ->fetchAssoc( $sql );
		 //print_r($result);exit;
			  foreach($result1  as $key=>$value){ 
			   
			    /*if($value['source']=='mtest' && $value['groupid']!=''){ 				    
					 $sql='select   a.*,b.schoolname from admin a left join school b on a.schoolid=b.schoolid
		where a.adminid="'.$value['adduserid'].'" and a.schoolid="'.$value['schoolid'].'" ';   
		      	     $res= $this->_dbAdapter->fetchRow($sql);  
					 $result[$key]['source'].='-'.$res['schoolname'].'-'.$res['adminname'];
				}else if($value['source']=='teacher'){
						  $sql="select * from  class_group_v where uid='".$value['adduserid']."'";
						  $res = $this->_dbAdapter->fetchRow ($sql);  
						  $result[$key]['source']=$res['groupname'].'-'.$res['schoolname'].'-'.$res['classname'];
				} else */if($value['source']=='parents'){
							  $sql="select * from  group_student_class_parents_v where ismainid=1 and pid='".$value['adduserid']."' and studentid=".$value['studentid'];
							  $res = $this->_dbAdapter->fetchRow ($sql);
							  //print_r($res);exit;   
							  $result1[$key]['source']=$res['groupname'].'-'.$res['schoolname'].'-'.$res['classname'].'-'.$res['cnname'].'-'.$res['realname'];
							  if($result1[$key]['studentid']){
								  $result[$key]=$value;
								  if($result1[$key]['source']){
									  $result[$key]['source']=$result1[$key]['source'];
								  }
							  }
						 }/*elseif($value['source']=='website'){
							 $result[$key]=$value;
						 }*/
		      }   
			   //print_r($result);print_r($result1);exit;
		        $this->view->result= $result;
    			$param ['file'] = '/' . $this->controller . '/' . $this->action;
    			$param ['totalnum'] = $this->_dbAdapter->fetchOne ( 'SELECT FOUND_ROWS()' ); 
    			$param ['perpagenum'] = $count; // 每页显示的数目
    			$param ['disnum'] = 11; // 取单数显示，当前页停在中间
    			$param ['curpage'] = $curpage; // 当前页码
				$this->view->allnum= $param ['totalnum'];

    			//	require_once 'MyClass/class.page.php';
    			$page = new MyClass_Page ( $param );
    		//	$page->setvar ( array ('year' => $year,'week'=>$week,'foodtimeid'=>$foodtimeid) );
				$this->view->page= $page->getNumPage ();
			 
			 
		
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), '注意', 'javascript:window.history.back();', 'warning' );
		}
	}
 
 
	public function applyAction() {
		try {
			
			$count = 20;
			$curpage = ( int ) $this->_request->getParam ( 'page' );
	     	if (! $curpage)
    				$curpage = 1;
			$this->view->pageNum=$curpage;		
    			$offset = ($curpage - 1) * $count; 
			$sql="select SQL_CALC_FOUND_ROWS *  from `feedback` where  isdelete=0  and source='website'  order by isover,addtime desc limit ".$offset.",".$count; 
			$result=$this->_dbAdapter ->fetchAssoc( $sql );
			$this->view->result= $result;
			$param ['file'] = '/' . $this->controller . '/' . $this->action;
			$param ['totalnum'] = $this->_dbAdapter->fetchOne ( 'SELECT FOUND_ROWS()' ); 
			$param ['perpagenum'] = $count; // 每页显示的数目
			$param ['disnum'] = 11; // 取单数显示，当前页停在中间
			$param ['curpage'] = $curpage; // 当前页码
			$this->view->allnum= $param ['totalnum'];

			//	require_once 'MyClass/class.page.php';
			$page = new MyClass_Page ( $param );
		//	$page->setvar ( array ('year' => $year,'week'=>$week,'foodtimeid'=>$foodtimeid) );
			$this->view->page= $page->getNumPage ();
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), '注意', 'javascript:window.history.back();', 'warning' );
		}
	}
 
 
 public function  opeditAction() {
		try {
          //提交反馈信息
		  if (! $this->isPost ()) {
					throw new Exception ( '参数错误！' ); 
		  }
		  $p =$this->_request->getPost ();

		  $neirong=$p['process'];		  
		  $p['feedbackid']=intval($p['feedbackid']);  
		  $sql="select  *  from feedback where feedbackid=".$p['feedbackid'];
		  $feedrow=$this->_dbAdapter->fetchRow($sql); 
		  //  print_r($feedrow); exit;
		  if(empty($p['optionsRadios'])){ 
			   throw new Exception ( '请选择问题类型！' );
		  } 
		
		  if(empty($p['feedbackid'])){ 
			   throw new Exception ( '参数错误！' );
		  } 
			    
		  if(empty($p['process'])) {
			   throw new Exception ( '内容不能为空！' );
		  }
		
			$now=date('Y-m-d H:i');
			$p['process']=str_replace("\n",'<br />', $p['process']);
			$p['process']='<p><span class="process">'.$p['process'].'</span><br />&nbsp;&nbsp;----';
			$p['process'] .=$this->_user->nickname.'['.$now.']</p>';
			$p['process']=addslashes(trim($p['process']));
		
            $sql='select process from feedback where feedbackid='.intval($p['feedbackid']);
			$content=$this->_dbAdapter->fetchRow($sql); 
			  		
			$data=array(
				'processtime'=>time(),
				'processuserid'=>$this->_user->id,	
				'nickname'=>$this->_user->adminname,
				'process'=>$p['process'].$content['process'],
				'type'=>$p['optionsRadios'],
				'isover'=>$p['typeselect'],
			);
			if($data) { 
				$result=$this->_dbAdapter->update('feedback',$data,'feedbackid='.$p['feedbackid']);  
				if(!$result){ 
					 throw new Exception ( '更新失败！' );
			    }
			}  
			//问题结束
			if($p['optionsRadios'] ) {  
			   $noticekey=$this->fast_uuid();  
			   if($feedrow['source'] == 'parents'){ 
					if( $p['optionsRadios']!=5){
						  $sql="select * from group_student_class_parents_v where ismainid=1 and pid=".$feedrow['adduserid']." and studentid=".$feedrow['studentid'];
						  $student_yunying = $this->_dbAdapter->fetchRow ($sql);    
				  
						  $noticearray=array();
						  $noticearray=array(
							 'schoolid'=>$student_yunying['schoolid'],
							 'classid'=>$student_yunying['classid'],
							 'noticekey'=>$noticekey,
							 'noticetitle'=>'[系统]您的反馈信息已经处理',
							 'noticecontent'=>'您的问题:'.$feedrow['content']."\n".'处理的结果:'.strip_tags($neirong)."，感谢您对云中校车的支持！",
							 'havestudent'=>'1', 
							 'addtime'=>time(),
							 'checktime'=>time(),
							 'adduserid'=>$this->_user ->id,
							 'checkuserid'=>$this->_user ->id,					 
							 'isteacher'=>'1',
							 'groupid'=>$student_yunying['groupid']
							); 
							$res = $this->_dbAdapter->insert ('notice',$noticearray);   
							$notice_student=array(
								'noticekey'=>$noticekey,
								'studentid'=>$student_yunying['studentid'],
								'addtime'=>time(),
							 	'groupid'=>$student_yunying['groupid']
							);
			  				$resa = $this->_dbAdapter->insert ('notice_student',$notice_student);  
				 			$result=$this->_dbAdapter->update('feedback',array('ispending'=>1),'feedbackid='.$p['feedbackid']);    
			       }else{
						$result=$this->_dbAdapter->update('feedback',array('isover'=>1),'feedbackid='.$p['feedbackid']);  				   				   }
			   }  
			 }
			 
		  if($result){ 
				$this->feedback ( 'success', 'success', '/'.$this->controller.'/index', 'tip', 3 );
		  }	else{
				throw new Exception ( '增加失败 ！' );	
		  }
   
        } catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), '注意', 'javascript:window.history.back();', 'warning' );
		}
	}
 
  private function fast_uuid($suffix_len=3){
        //! 计算种子数的开始时间
        static $being_timestamp = 1216681180;// 2012-5-10
       
        $time = explode(' ', microtime());
        $id = ($time[1] - $being_timestamp) . sprintf('%06u', substr($time[0], 2, 6));
        if ($suffix_len > 0)
        {
            $id .= substr(sprintf('%010u', mt_rand()), 0, $suffix_len);
        }
        return $id;
 }
            
public function  editAction() {
		try {
       // print_r($this->_user);
		$id = ( int ) $this->_request->getParam ( 'id' );
		 
		if (! $id){
				throw new Exception ( 'parameter_error' );
			}else{
		    
			$sql="SELECT * FROM `feedback` where  isdelete=0  and  feedbackid='".$id."' ";
			$result=$this->_dbAdapter ->fetchRow( $sql );  
			// print_r($result);
/*			if($result['source']=='mtest' && $result['groupid']!=''){ 
				//$sql="select * from groups where groupid=".$result['groupid'];
				//$groupsres = $this->_dbAdapter->fetchRow ($sql); 
			    
				//$yunyingDb=$this->getDbLink($result['groupid']);
				//$yunyingDb->query ( 'set names utf8'); 
				 $sql='select   a.*,b.schoolname from admin a left join school b on a.schoolid=b.schoolid
	where a.adminid="'.$result['adduserid'].'" and a.schoolid="'.$result['schoolid'].'" ';   
				 $res= $this->_dbAdapter->fetchRow($sql);  
				 $result['source'].='-'.$res['schoolname'].'-'.$res['adminname'];
					 
				  }else if($result['source']=='teacher'){
					
					  $sql="select * from  class_group_v where uid='".$result['adduserid']."'";
					  $res = $this->_dbAdapter->fetchRow ($sql);  
					  $result['source']=$res['groupname'].'-'.$res['schoolname'].'-'.$res['classname'];
				
				 } else */if($result['source']=='parents'){
					  $sql="select * from  group_student_class_parents_v where ismainid=1 and pid='".$result['adduserid']."' and studentid=".$result['studentid'];
					  $res = $this->_dbAdapter->fetchRow ($sql);   
					  $result['source']=$res['groupname'].'-'.$res['schoolname'].'-'.$res['classname'].'-'.$res['cnname'].'-'.$res['realname'];
					 } 
			
			 $this->view->result=$result;	
			 //print_r($result);exit; 
			}
		 
		   
        } catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), '注意', 'javascript:window.history.back();', 'warning' );
		}
	}

	//用户首页
	public function  deleteAction() {
		try {
			//获取用户id
			$id = ( int ) $this->_request->getParam ( 'id' );
			if (! $id){
				throw new Exception ( 'parameter_error' );
			}else{         
		 
			   $data=array(
					'isdelete'=>'1', 
				);
			$res=$this->_dbAdapter->update('feedback',$data,'feedbackid='.$id );
			
		  if($res){ 
				$this->feedback ( 'success', 'success', '/'.$this->controller.'/index', 'tip', 3 );
			  }	else{
				throw new Exception ( '增加失败 ！' );	
				  }
				 
				
			}
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), '注意', 'javascript:window.history.back();', 'warning' );
		}
	}
 /*查找所有的学生信息*/
 
    
 
	
	/*
	新增功能 ---增加反馈信息
	*/
    public function  addAction() {
		try {
           $where='where  ismainid=1 ';	
			 
		   $groupid = ( int ) $this->_request->getParam ( 'groups' );
		   $school_id = $this->_request->getParam ( 'school' ); 		
	       $classid  = $this->_request->getParam ( 'class' ); 
		   $cnname  = $this->_request->getParam ( 'cnname' ); 
		    if($groupid){
		  $this->view->groups=$groupid; 
		  $this->view->school_id=$school_id;  
		  $this->view->classid=$classid; 
		  $this->view->cnname=$cnname; 
		  
				  if($school_id){ 
					  $schoolarray=explode('_',$school_id);  
					  $schoolid=$schoolarray['0'];
				  }
				   
				 if($groupid){
					  $where .=' and  groupid="'.$groupid.'" ';
					  $this->view->groupid= $groupid; 
					 }
					 
				 if($schoolid){
					$where .=' and  schoolid="'.$schoolid.'" '; 
					$this->view->schoolid= $schoolid; 
					} 
					
				 if($classid){
					$where .=' and  classid="'.$classid.'" ';
					  $this->view->classid= $classid; 
					 }	
					 
				 if($cnname){
					$where.=' and cnname="'.trim($cnname).'" ';
					$this->view->cnname= $cnname; 				 
					} 
			  
			$count = 20;
			$curpage = ( int ) $this->_request->getParam ( 'page' );
	     	if (! $curpage)
    				$curpage = 1;
			  $this->view->pageNum= $curpage;			
					
    			$offset = ($curpage - 1) * $count; 
			    $sql="select SQL_CALC_FOUND_ROWS student_uid,cnname  from group_student_class_parents_v ".$where."  order by pid ASC limit $offset,$count";
			   
			    $result = $this->_dbAdapter->fetchAll ($sql);  
			   
		    	$this->view->result= $result;
				$param ['file'] = '/' . $this->controller . '/' . $this->action;
    			$param ['totalnum'] = $this->_dbAdapter->fetchOne ( 'SELECT FOUND_ROWS()' ); 
    			$param ['perpagenum'] = $count; // 每页显示的数目
    			$param ['disnum'] = 11; // 取单数显示，当前页停在中间
    			$param ['curpage'] = $curpage; // 当前页码
				$this->view->allnum= $param ['totalnum'];

    			//	require_once 'MyClass/class.page.php';
    			$page = new MyClass_Page ( $param );
    			$page->setvar ( array ('groups' => $groupid,'school'=>$schoolid,'class'=>$classid) );
			    $this->view->page= $page->getNumPage ();
             } 
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), '注意', 'javascript:window.history.back();', 'warning' );
		}
	}

/*处理手动添加的反馈信息*/

    public function  addopAction() {
		try {

			if (! $this->isPost ()) {
					throw new Exception ( '参数错误！' );
			}
			
			$p =$this->_request->getPost ();
             
			 if($p['content'] ==''){
				 echo -2; exit;
				 }
	  
			if($p['q_type'] ==''){
				 echo -3; exit;
				 }
			if($p['typelist'] ==''){
				 echo -4; exit;
				 }
		   if($p['uid'] ==''){
				 echo -5; exit;
				 }
			
				 	 
			$t=time(); 
			$data=array(
			    'nickname'=>$this->_user->adminname,
				'process'=>$p['process'],
				'source'=>'parents',
				'adduserid'=>$p['uid'],
			    'processuserid'=>$this->_user->id,
			    'addtime'=>$t,
				'content'=>$p['content'],
				'processtime'=>$t,
				'isstudent'=>$t, 
				'type'=>$p['typelist'],
				'iswrite'=>'1'
				 );
				  
			if($p['q_type']=='1'){
               // $data['ispending']=1; 
 			  }else if($p['q_type']=='2'){
				$data['ispending']=1; 
			  }else if($p['q_type']=='4'){
				$data['isover']=1;	
				 //发布通知----
				 $noticekey=$this->fast_uuid();  
				
				 $sql="select * from  student  where uid=".$p['uid'];
				 $studentAll = $this->_dbAdapter->fetchRow ($sql);  
				 
				 //$yunyingDb=$this->getDbLink($studentAll['groupid']);
				 //$yunyingDb->query ( 'set names utf8');	 
				
				$sql="select * from student where uid=".$studentAll['uid'];
		        $student_yunying = $this->_dbAdapter->fetchRow ($sql);
				
			      $noticearray=array();
				  $noticearray=array(
				     'schoolid'=>$student_yunying['schoolid'],
					 'classid'=>$student_yunying['classid'],
					 'noticekey'=>$noticekey,
					 'noticetitle'=>'[系统]您的反馈信息已经处理',
					 'noticecontent'=>'您的问题:'.$p['content']."\n".'处理的结果:'.strip_tags($p['process'])."，感谢您对云中校车的支持！",
				     'havestudent'=>'1', 
					 'addtime'=>time(),
					 'checktime'=>time(),
					 'adduserid'=>$this->_user ->id,
					 'checkuserid'=>$this->_user ->id,					 
					 'isteacher'=>'1'
				    ); 
				$res = $this->_dbAdapter->insert ('notice',$noticearray);   
				$notice_student=array(
					'noticekey'=>$noticekey,
					'studentid'=>$student_yunying['studentid'],
					'addtime'=>time(),
				);
			  $res_student = $this->_dbAdapter->insert ('notice_student',$notice_student);   
			  }  
		      
			$result = $this->_dbAdapter->insert ('feedback',$data);   
           	
		  if($result){ 
				//$this->feedback ( 'success', 'success', '/'.$this->controller.'/index', 'tip', 3 );
				echo '1';   exit;
				
			  }	else{
				 echo '-1';   exit;
			  }
				 
			 
	} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), '注意', 'javascript:window.history.back();', 'warning' );
		}
	}




/*
 查询某个学生
*/

public function groupsAction() {
		try { 
         
		 $sql="select * from  groups ";
	     $result = $this->_dbAdapter->fetchAll ($sql);
		 
		 for($i = 0; $i<count($result); $i++)
		{
	      $str .= "<option value='".$result[$i]['groupid']."'>".$result[$i]['groupname']."</option>";
		}
		
	    echo $str;  exit;
	} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	//获取所有的校园列表
	  public function schoollistAction() {
		try { 
           if (! $this->isPost ()) {
					throw new Exception ( '参数错误！' );
			}			
		  $p =$this->_request->getPost ();  
		 
		  $sql="SELECT * FROM `groups` where groupid='".$p['id']."' ";
		  $result = $this->_dbAdapter->fetchRow ($sql);
	 
/*			//连接运营库
			$dbArray=array();
			$dbArray['host']=$result['dbhost'];
			$dbArray['username']=$result['dbusername'];
			$dbArray['password']=$this->authcode($result['dbpassword'], 'DECODE', 'mactop') ;
			$dbArray['dbname']=$result['dbname'];
			
			$dbAdapter = Zend_Db::factory ("PDO_MYSQL", $dbArray );
			Zend_Registry::set('dbAdapter', $dbAdapter);

			$dbAdapter=Zend_Registry::get('dbAdapter');
			$dbAdapter->query ( 'set names utf8');	
*/			 
		    $sql="select * from  school groupid='".$p['id']."'";   
			$schoollist= $dbAdapter->fetchAll ($sql);
	                 

			 
		 for($i = 0; $i<count($schoollist); $i++)
		{
		  $str .= "<option value='".$schoollist[$i]['schoolid'].'_'.$result['groupid']."'>".$schoollist[$i]['schoolname']."</option>";
		}
		   
	      echo $str;  exit;
	} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	
	
	//获取所有的班级信息
	  public function classlistAction() {
		try { 
           if (! $this->isPost ()) {
					throw new Exception ( '参数错误！' );
			}			
		  $p =$this->_request->getPost ();  
		  $array=explode('_',$p['id']);
		  
		  $sql="SELECT * FROM `groups` where groupid='".$array['1']."' ";
		  $result = $this->_dbAdapter->fetchRow ($sql);
	 
			//连接运营库
/*			$dbArray=array();
			$dbArray['host']=$result['dbhost'];
			$dbArray['username']=$result['dbusername'];
			$dbArray['password']=$this->authcode($result['dbpassword'], 'DECODE', 'mactop') ;
			$dbArray['dbname']=$result['dbname'];
			
			$dbAdapter = Zend_Db::factory ("PDO_MYSQL", $dbArray );
			Zend_Registry::set('dbAdapter', $dbAdapter);

			$dbAdapter=Zend_Registry::get('dbAdapter');
			$dbAdapter->query ( 'set names utf8');	
*/			 
		  $sql="select * from  class  where isdel=0 and schoolid='".$array['0']."' ";   
		  $classlist= $this->_dbAdapter->fetchAll ($sql);
	  
			 
		 for($i = 0; $i<count($classlist); $i++)
		{
		  $str .= "<option value='".$classlist[$i]['classid']."'>".$classlist[$i]['classname']."</option>";
		}
		   
	      echo $str;  exit;
	} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}



	 //以下内容保持不变
	public function noRouteAction() {
		$this->_redirect ( '/' );
	}
	
	public function __call($method, $args) {
		if ('Action' == substr ( $method, - 6 )) {
			$url = '/' . $this->controller . '/index';
			return $this->_redirect ( $url );
		}
		throw new Exception ( 'Invalid method' );
	}
}

